﻿#include "mainwindow.h"
#include <QQuickView>
#include <QQmlEngine>
#include <QQmlContext>
// CTKPluginFramework includes
#include "ctkPluginContext.h"
#include <ctkException.h>
#include "PluginInterfaces.h"
#include "common.h"

MainWindow::MainWindow(ctkPluginContext *context, QObject *parent)
    :m_context(context)
    , m_mainManager(new MainManager(this))
{
    startListening();
}

MainWindow::~MainWindow()
{

}

void MainWindow::startAppWithArgs(const QStringList& fileList)
{
    m_view.setTitle(common::getApplicationName());
    //m_view.setMinimumSize({ 600, 480 });

    m_view.rootContext()->setContextProperty("view", &m_view);
    m_view.rootContext()->setContextProperty("mainManager", m_mainManager);

    QUrl url(QStringLiteral("qrc:/qml/main.qml"));
#ifdef Q_OS_MAC
    url.setUrl(QStringLiteral("qrc:/qml/main_mac.qml"));
    QString mUrlStr = QGuiApplication::applicationDirPath() + "/../Resources/qml";
    m_view.engine()->addImportPath(mUrlStr);
#endif
    //, &splash
    QObject::connect(&m_view, &QQuickView::statusChanged, &m_view, [this](QQuickView::Status status) {
        if (status == QQuickView::Status::Ready) {
            qDebug() << "qml load finish!";
        }
    });

    QObject::connect(m_view.engine(), &QQmlEngine::quit, qApp, [](){
        QApplication::quit();
    });
    QObject::connect(qApp, &QApplication::aboutToQuit, qApp, [this](){
        m_view.setSource({});
    });

    m_view.setSource(url);
    m_view.moveToScreenCenter();
    m_view.show();
    m_mainManager->postCtkEvent(MAINWINDOW_LOAD);
}

void MainWindow::quitApp()
{
    QApplication::quit();
}

void MainWindow::TestInterface()
{
	qDebug() << "test interface";
}


///////////////////////////////////////////////////事件处理////////////////////////////////////////////////////////
void MainWindow::startListening(){
    ctkDictionary dic;
	// 需要和谁通信，这里将字段加入监听队列
    dic.insert(ctkEventConstants::EVENT_TOPIC, TOPIC_HELLOWORD);
    m_context->registerService<ctkEventHandler>(this, dic);
    // CTK通讯的线程不是主UI线程,这里需要将信号发送到主界面的UI线程上来
    connect(this, &MainWindow::handleCtkEvent, this, &MainWindow::onCtkEvent, Qt::QueuedConnection);
}

void MainWindow::handleEvent(const ctkEvent& event){
    emit handleCtkEvent(event);
}

void MainWindow::onCtkEvent(const ctkEvent& event)
{
    QString topic = event.getTopic();
    QString eventStr = event.getProperty("EVENT").toString();
    if(eventStr.contains(HELLOWORD_STRING)) {
        emit m_mainManager->testSignals(event.getProperty(PROPERTY_DATA).toString());
    }
}

ctkEventAdmin* MainWindow::getEventAdmin()
{
    ctkServiceReference ref;
    ctkEventAdmin *eventAdmin = nullptr;

    try {
        ref = m_context->getServiceReference<ctkEventAdmin>();
    }  catch (const ctkServiceException& e) {
        qCritical() << e.printStackTrace();
    } catch (...) {
        qCritical() << "Unknown exception.";
    }

    if (ref) {
        eventAdmin = m_context->getService<ctkEventAdmin>(ref);
        m_context->ungetService(ref);
    } else {
        qCritical() << "Get ctkEventAdmin error.";
    }

    return eventAdmin;
}

void MainWindow::postCtkEvent(const QString event, const QVariant data, const QVariant extentionData)
{
	ctkEventAdmin *eventAdmin = getEventAdmin();
    if(eventAdmin != nullptr){
        ctkDictionary dic;
        dic.insert(PROPERTY_EVENT, event);
        dic.insert(PROPERTY_DATA, data);
        dic.insert(PROPERTY_EXTENTION, extentionData);
        eventAdmin->postEvent(ctkEvent(TOPIC_MAINWINDOW, dic));
    }
}
